import { ref, watch } from 'vue'
import { themes, type Theme } from '@/styles/themes'

const THEME_STORAGE_KEY = 'future-diary-theme'
const defaultTheme = themes.find((theme) => theme.id === 'dark-matter') || themes[0]

// 创建响应式主题状态
const currentTheme = ref<Theme>(
  themes.find((theme) => theme.id === localStorage.getItem(THEME_STORAGE_KEY)) || defaultTheme,
)

// 应用主题到 DOM
const applyTheme = (theme: Theme) => {
  const root = document.documentElement
  Object.entries(theme.colors).forEach(([key, value]) => {
    root.style.setProperty(`--${key}`, value)
  })
}

// 监听主题变化
watch(
  () => currentTheme.value,
  (newTheme) => {
    applyTheme(newTheme)
    if (newTheme === defaultTheme) {
      localStorage.removeItem(THEME_STORAGE_KEY)
    } else {
      localStorage.setItem(THEME_STORAGE_KEY, newTheme.id)
    }
  },
  { immediate: true },
)

// 导出主题管理器
export function useTheme() {
  const setTheme = (themeId: string) => {
    if (themeId === 'default' || currentTheme.value.id === themeId) {
      currentTheme.value = defaultTheme
      return
    }
    const theme = themes.find((t) => t.id === themeId)
    if (theme) {
      currentTheme.value = theme
    }
  }

  return {
    themes,
    currentTheme,
    setTheme,
    defaultTheme,
  }
}
